unit MVC.HttpServer;

interface

uses
  SysUtils, Classes, mvc.Config, fphttpserver, fpmimetypes;

type
  TWebRequest = TFPHTTPConnectionRequest;
  TWebResponse = TFPHTTPConnectionResponse;

  TMVCServer = class
  public
    FStop: boolean;
    FHttpServer: TFPHttpServer;
    procedure DoIdle(Sender: TObject);
    procedure HandleRequest(Sender: TObject; var req: TFPHTTPConnectionRequest;
      var res: TFPHTTPConnectionResponse);
    constructor Create;
    destructor Destroy; override;
    class procedure Start;
    class procedure Stop;
  end;

var
  Serv: TMVCServer;

implementation

uses mvc.Route;

procedure TMVCServer.DoIdle(Sender: TObject);
begin
  if FStop then
    FHttpServer.Active := False;
end;


procedure TMVCServer.HandleRequest(Sender: TObject; var req: TFPHTTPConnectionRequest;
  var res: TFPHTTPConnectionResponse);
var
  error: string;
begin

  try
    if FStop then
    begin
      FHttpServer.Active := False;
      exit;
    end;
    route.OpenRoute(req, res);

  except
    on e: Exception do
    begin
      error := e.Message;
      Route.Error500(res, error);
    end;

  end;

end;

constructor TMVCServer.Create;
begin
  FHttpServer := TFPHttpServer.Create(nil);
end;

destructor TMVCServer.Destroy;
begin
  FHttpServer.Free;
  inherited Destroy;
end;

class procedure TMVCServer.Start;
begin
  Serv := TMVCServer.Create;

  try
    Serv.FStop := False;
    Serv.FHttpServer.Threaded := True;
    Serv.FHttpServer.Port := Config.Port.ToInteger;
    Serv.FHttpServer.QueueSize := Config.ThreadCount;
    Serv.FHttpServer.AcceptIdleTimeout := 500;
    Serv.FHttpServer.OnAcceptIdle := @Serv.DoIdle;
    Serv.FHttpServer.OnRequest := @Serv.HandleRequest;

    Serv.FHttpServer.Active := True;
  finally
    Serv.Free;
  end;
end;

class procedure TMVCServer.Stop;
begin
  Serv.FStop := True;
end;

end.
